#include "linkfabric/TLV.hpp"
#include <cstring>

using namespace linkfabric;

TLV::TLV(uint8_t t, const std::vector<uint8_t>& v)
  : tag(t), length(static_cast<uint16_t>(v.size())), value(v) {}

std::vector<uint8_t> TLV::encode() const {
    std::vector<uint8_t> out;
    out.reserve(1 + 2 + length);
    out.push_back(tag);
    out.push_back(static_cast<uint8_t>(length >> 8));
    out.push_back(static_cast<uint8_t>(length & 0xFF));
    out.insert(out.end(), value.begin(), value.end());
    return out;
}

TLV TLV::decode(const std::vector<uint8_t>& raw, size_t& offset) {
    uint8_t t = raw[offset++];
    uint16_t len = (static_cast<uint16_t>(raw[offset++]) << 8) |
                    static_cast<uint16_t>(raw[offset++]);
    std::vector<uint8_t> v(raw.begin() + offset, raw.begin() + offset + len);
    offset += len;
    return TLV(t, v);
}